package com.taptech.doufu.presenter.home;

import android.app.Activity;
import android.content.Context;

import com.google.gson.Gson;
import com.taptech.doufu.constant.HomePageType;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.bean.DFHomeNovelBeans;
import com.taptech.doufu.bean.DFHomeNovelContentBeans;
import com.taptech.doufu.bean.cp.ResponseCpIndexDataBean;
import com.taptech.doufu.listener.CommmonImp;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.util.GsonUtil;
import com.taptech.doufu.ui.view.topicview.NovelTopicType;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Wyatt on 2017/10/13/013.
 */

public class HomeTopicPresenter {
    public interface OnHomeTopicView{
        void onTopicNext(List<Object> list,boolean isCache);
        void onTopicError();
    }

    private OnHomeTopicView onHomeTopicView;
    private Context mContext;
    private String pageType;

    public HomeTopicPresenter(Context context,String pageType,OnHomeTopicView onHomeTopicView) {
        this.onHomeTopicView = onHomeTopicView;
        mContext = context;
        this.pageType = pageType;
    }


    private String getUrl() {
        if (HomePageType.RAINBOW_FINISHED.equals(pageType)){
            return "/index.php/new_home/new_home/recommend?sexType=1&type=finished";
        }else if (HomePageType.COPYRIGHT.equals(pageType)){
            return "/new_home/new_home/recommend/?type=copyright";
        }else if(HomePageType.RAINBOW.equals(pageType)){
            return "/index.php/new_home/new_home/recommend?sexType=1";
        }else{
            return "/index.php/new_home/new_home/recommend?sexType=3";
        }
    }

    private String getCachePath() {
        if (HomePageType.RAINBOW_FINISHED.equals(pageType)){
            return CommmonImp.Home_novel_list1_finished;
        }else if (HomePageType.COPYRIGHT.equals(pageType)){
            return CommmonImp.Home_novel_copyright;
        }else if(HomePageType.RAINBOW.equals(pageType)){
            return CommmonImp.Home_novel_list1;
        }else{
            return CommmonImp.Home_novel_un_list1;
        }
    }

    public void loadTopicCache(final String sexType) {
        Observable.create((Observable.OnSubscribe<List<Object>>) subscriber -> {
            JSONObject json = CacheUtil.readJsonDataFromCache(new File(getCachePath()));
            List<Object> list = formatData(GsonUtil.parseJsonWithGson(json.toString(), ResponseCpIndexDataBean.class));
            subscriber.onNext(list);
        })
                .compose(RxJavaHelper.<List<Object>>observeOnMainThread((Activity) mContext))
                .subscribe(new BaseSubscriber<List<Object>>(){
                    @Override
                    public void onNext(List<Object> objects) {
                        super.onNext(objects);
                        if (onHomeTopicView != null) {
                            onHomeTopicView.onTopicNext(objects,true);
                        }
                    }
                });
    }

    /**
     * 获取话题数据
     */
    public void getHomeNovelTopic(boolean isUseCache, final String sexType) {
        ApiClient.getInstance().setUseCache(isUseCache).setSexType(sexType).getService().getNovelTopic(getUrl())
                .map(responseCpIndexDataBean -> {
                    CacheUtil.saveJsonDataToCache(new Gson().toJson(responseCpIndexDataBean),new File(getCachePath()));
                    return formatData(responseCpIndexDataBean);
                })
                .compose(RxJavaHelper.<List<Object>>observeOnMainThread((Activity) mContext))
                .subscribe(new BaseSubscriber<List<Object>>(){
                    @Override
                    public void onNext(List<Object> objects) {
                        super.onNext(objects);
                        if (onHomeTopicView != null) {
                            onHomeTopicView.onTopicNext(objects,false);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (onHomeTopicView != null) {
                            onHomeTopicView.onTopicError();
                        }
                    }
                });
    }


    public void getHomeGAYNovelTopic(boolean isUseCache) {
        ApiClient.getInstance().setUseCache(isUseCache).getService().getCpIndexData()
                .map(responseCpIndexDataBean -> {
                    CacheUtil.saveJsonDataToCache(new Gson().toJson(responseCpIndexDataBean),new File(CommmonImp.Home_novel_gay_list1));
                    return formatData(responseCpIndexDataBean);
                })
                .compose(RxJavaHelper.<List<Object>>observeOnMainThread((Activity) mContext))
                .subscribe(new BaseSubscriber<List<Object>>() {
                    @Override
                    public void onNext(List<Object> t) {
                        super.onNext(t);
                        if (onHomeTopicView != null) {
                            onHomeTopicView.onTopicNext(t,false);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (onHomeTopicView != null) {
                            onHomeTopicView.onTopicError();
                        }
                    }
                });
    }




    /**
     * 格式化数据
     *
     * @param responseCpIndexDataBean
     */
    private List<Object> formatData(ResponseCpIndexDataBean responseCpIndexDataBean) {
        List<Object> contentAdaList = new ArrayList<>();
        List<ResponseCpIndexDataBean.DataBean.ListBean> cpneDatalist = new ArrayList<>();
        List<ResponseCpIndexDataBean.DataBean.ListBean> cpDatalist = responseCpIndexDataBean.getData().getList();
        for(int i=0;i < cpDatalist.size();i++) {
            ResponseCpIndexDataBean.DataBean.ListBean model = cpDatalist.get(i);
            if (model.getModel() == NovelTopicType.TFHomeNovelModelTypeTag) {
                contentAdaList.add(model);
            } else if (model.getModel() == NovelTopicType.TFHomeNovelModelTypeBanner) {
                contentAdaList.add(model);
            }else{
                cpneDatalist.add(model);
            }
        }
        List<DFHomeNovelContentBeans> content1List = com.alibaba.fastjson.JSONArray.parseArray(new Gson().toJson(cpneDatalist), DFHomeNovelContentBeans.class);
        changeData(content1List,contentAdaList);
        return contentAdaList;
    }

    //将content1List转换为contentAdaList
    private synchronized void changeData(List<DFHomeNovelContentBeans> tempList,List<Object> target) {
        try {
            if ((tempList != null) && (tempList.size() > 0)) {
                for (int i = 0; i < tempList.size(); i++) {
                    if ((tempList.get(i).getList() != null) && (tempList.get(i).getList().size() > 0)) {
                        if (tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModelTypeSale||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModelTypeNovelRank||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModelTypeNovelSingle||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModelTypeNovelLastest||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeBookList||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeImage||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeLimitTime||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeCategorty||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeCategortyPlus||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeTwoLine||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeDSRecommend||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeTopRank||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeComic||
                                tempList.get(i).getModel() == NovelTopicType.TFHomeNovelModeTypeHSRecommend){
                            target.add(tempList.get(i));
                        }else{
                            boolean isShowTag = tempList.get(i).isTag();
                            for (int j = 0; j < tempList.get(i).getList().size(); j++) {
                                DFHomeNovelBeans cateBean= tempList.get(i).getList().get(j);
                                if (0 == j) {
                                    cateBean.hasTitleA = true;
                                    cateBean.upTitleNameA = tempList.get(i).getTitle();
                                    if ((tempList.get(i).getMore_url() != null) && (tempList.get(i).getMore_url().length() > 0)) {
                                        cateBean.isMoreUrlA = true;
                                        cateBean.moreUrlAddress = tempList.get(i).getMore_url();
                                    } else {
                                        cateBean.isMoreUrlA = false;
                                    }
                                } else {
                                    cateBean.hasTitleA = false;
                                    cateBean.isMoreUrlA = false;
                                }
                                cateBean.isShowTag = isShowTag;

                                if (j == (tempList.get(i).getList().size() - 1)) {
                                    cateBean.isShowLine = false;
                                }
                                target.add(cateBean);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
